/* This file is part of swapper project
 *
 * Copyright (C) 2020 The Swapper Project Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package com.swapper.json.spi.supports;

import com.swapper.json.*;

import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

/**
 * The {@link Object} wrapper factory.
 */
public enum ObjectWrapperFactory implements JsonWrapperFactory {
  INSTANCE;

  @SuppressWarnings("unchecked")
  @Override
  public <T> JsonWrapper<T> create(JsonContext context, Type type) {
    return type == Object.class ? (JsonWrapper<T>) new ObjectWrapper(context) : null;
  }

  private static final class ObjectWrapper implements JsonWrapper<Object> {
    private final JsonContext context;

    public ObjectWrapper(JsonContext context) {
      this.context = context == null ? JsonContext.getDefault() : context;
    }

    @Override
    public JsonValue wrap(Object value) {
      if (value == null) {
        return JsonValue.NULL;
      } else if (value instanceof JsonValue) {
        return (JsonValue) value;
      } else {
        return context.findWrapper(value.getClass()).wrap(value);
      }
    }

    @Override
    public Object unwrap(JsonValue value) {
      if (JsonValue.NULL.equals(value)) {
        return null;
      } else if (JsonValue.TRUE.equals(value)) {
        return Boolean.TRUE;
      } else if (JsonValue.FALSE.equals(value)) {
        return Boolean.FALSE;
      } else if (value instanceof JsonNumber) {
        return value.toNumber();
      } else if (value instanceof JsonString) {
        return value.toString();
      } else if (value instanceof JsonArray) {
        return context.findWrapper(List.class).unwrap(value);
      } else if (value instanceof JsonObject) {
        return context.findWrapper(Map.class).unwrap(value);
      }
      return value;
    }
  }
}
